package com.ucode.tool.util;

import java.util.HashMap;
import java.util.Map;
import com.alibaba.ttl.TransmittableThreadLocal;

/**
 * 父子线程参数传递、跨线程池传递参数
 * https://github.com/alibaba/transmittable-thread-local
 * @author: liliang
 * @date: 2020年1月31日 下午1:09:51
 */
public class TransmittableThreadLocalUtil {

    public static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL = new TransmittableThreadLocal<Map<String, Object>>();

    public static void set(Map<String, Object> value){
        Map<String, Object> map = THREAD_LOCAL.get();
        if(map != null){
            map.putAll(value);
            THREAD_LOCAL.set(map);
        }else{
            THREAD_LOCAL.set(value);
        }
    }
    
    public static void set(String key,Object value) {
        Map<String, Object> map = THREAD_LOCAL.get();
        if(map != null){
            THREAD_LOCAL.get().put(key, value);
        }else{
            map = new HashMap<String, Object>();
            map.put(key, value);
            THREAD_LOCAL.set(map);
        }
    }
    
    public static Map<String, Object> get() {
        return THREAD_LOCAL.get();
    }

    public static Object get(String key) {
        Map<String, Object> map = get();
        
        if(map != null && map.containsKey(key)){
            return map.get(map);
        }
        return null;
    }

    public static void remove() {
        THREAD_LOCAL.remove();
    }
    
    public static void remove(String key) {
        Map<String, Object> map = THREAD_LOCAL.get();
        if(map != null){
            THREAD_LOCAL.get().remove(key);
        }
    }
    
}